package com.base.cn.platform.os.controller.web.course.cou;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.constants.CacheConstants;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.count.PageFrom;
import com.base.cn.platform.os.common.utils.count.PageKeyUtils;
import com.base.cn.platform.os.common.utils.course.CourseContentUtil;
import com.base.cn.platform.os.common.utils.course.CourseType;
import com.base.cn.platform.os.common.utils.order.ShopType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.op.coupon.OpCoupon;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogService;
import com.base.cn.platform.os.service.course.classes.ClassesService;
import com.base.cn.platform.os.service.course.comment.CourseCommentService;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import com.base.cn.platform.os.service.course.cou.packageCou.PackageCourseService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.count.PageViewCountService;
import com.base.cn.platform.os.service.manage.op.coupon.OpCouponService;
import com.base.cn.platform.os.service.manage.teacher.SysTeacherService;
import com.base.cn.platform.os.service.upload.LoggerGenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 课程前台Controller
 *
 * @author s.li
 * @create 2018-05-10-19:39
 */
@Controller
@RequestMapping("/web/course")
public class WebCourseController extends WebBaseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseCatalogService courseCatalogService;
    @Autowired
    private CourseBuyRecordService courseBuyRecordService;
    @Autowired
    private PackageCourseService packageCourseService;
    @Autowired
    private PageViewCountService pageViewCountService;
    @Autowired
    private SysTeacherService sysTeacherService;
    @Autowired
    private CourseCommentService courseCommentService;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    @Autowired
    private LoggerGenService loggerGenService;
    @Autowired
    private SysConfigService  sysConfigService;
    @Autowired
    private OpCouponService opCouponService;
    @Autowired
    private ClassesService classesService;

    /**
     * 直播列表
     *
     * @return
     */
    @RequestMapping("/liveIndex")
    public String newLiveList(Model model){
        return resultPage("/course/live/live-index");
    }

    /**
     * 加载课程数据
     * @param model Model
     * @param params 查询条件
     * @param currentPage 页码
     * @return String
     */
    @RequestMapping("/ajaxLiveList")
    public String ajaxLiveList(Model model,
                                 @RequestBody Map<String, Object> params,
                                 @RequestParam("currentPage") int currentPage) {
        params.put("status", 1);
        params.put("type", 1);
        params.put("courseTypeKey", CourseType.COURSE_TYPE_LIVE.getKey());
        Map<String, Object> dataMap = courseService.findWebCoursePage(params, currentPage, 6, true, false, false, true,true);
        model.addAttribute("dataMap", dataMap);
        return resultPage("/course/live/ajax-live-index");
    }

    /**
     * 直播详情页
     *
     * @return
     */
    @RequestMapping("/liveInfo")
    public String newLiveInfo(HttpServletRequest request,
                              Model model,@RequestParam("courseId") BigDecimal courseId){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> course = courseService.findToBuyCourseById(courseId, userId,true, true, true, false, false, true,true);
        pageViewCountService.addPageCount(PageKeyUtils.COURSE_INFO, PageFrom.PAGE_FROM_PC);
        request.setAttribute("mobilePathShare", "/mobile/course/liveInfo?courseId="+courseId);
        model.addAttribute("course",course);
        course.put("courseService",CourseContentUtil.setCourseService(Integer.valueOf(course.get("service").toString()),sysConfigService," . "));
        loggerGenService.genGoodsPVUVLog(courseId, ShopType.ORDER_SHOP_COURSE);
        model.addAttribute("classes", classesService.getCourseRelevanceClasses(courseId));
        return resultPage("/course/live/live-info");
    }

    /**
     * 课程列表
     *
     * @return
     */
    @RequestMapping("/courseList")
    public String courseList(Model model ,
                             @RequestParam(value="courseName",required = false, defaultValue = "") String courseName,
                             @RequestParam(value="courseTypeKey",required = false, defaultValue = "") String courseTypeKey) {
        model.addAttribute("year", Calendar.getInstance().get(Calendar.YEAR) + 2);
        model.addAttribute("courseName", courseName);
        model.addAttribute("courseTypeKey", courseTypeKey);
        model.addAttribute("courseTypeList", CourseType.values());
        return resultPage("/course/cou/course-list");
    }

    /**
     * 加载课程数据
     *
     * @param model Model
     * @param params 查询条件
     * @param currentPage 页码
     * @return String
     */
    @RequestMapping("/ajaxCourseList")
    public String ajaxCourseList(Model model,
                                 @RequestBody Map<String, Object> params,
                                 @RequestParam("currentPage") int currentPage) {
        params.put("status", 1);
        params.put("type", 1);
        params.put("notCourseTypeKey", CourseType.COURSE_TYPE_LIVE.getKey());
        Map<String, Object> dataMap = courseService.findWebCoursePage(params, currentPage, 8, false, false, false, true,false);
        model.addAttribute("dataMap", dataMap);
        return resultPage("/course/cou/ajax-course-list");
    }

    /**
     * 课程详情
     * @param request HttpServletRequest
     * @param model Model
     * @param courseId 课程ID
     * @return 详情页面
     */
    @RequestMapping("/courseInfo")
    public String courseInfo(HttpServletRequest request,
                             Model model,
                             @RequestParam("courseId") BigDecimal courseId) {
        //用户ID
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        request.setAttribute("mobilePathShare", "/mobile/course/info?courseId="+courseId);
        Map<String, Object> course = courseService.findToBuyCourseById(courseId, userId,true, true, true, false, false, false,false);
        Map<String, Object> params = new HashMap<>();
        params.put("courseId",courseId);
        params.put("status",1);
        BigDecimal commentCount = courseCommentService.findCommentCount(params);
        model.addAttribute("commentCount", commentCount);
        course.put("courseService",CourseContentUtil.setCourseService(Integer.valueOf(course.get("service").toString()),sysConfigService," . "));
        model.addAttribute("course", course);
        pageViewCountService.addPageCount(PageKeyUtils.COURSE_INFO, PageFrom.PAGE_FROM_PC);
        String classesUrl = (String) customCacheChannel.get(J2CacheRegion.THIRD_MINUTE_REGION.getKey(), CacheConstants.USER_BUY_COURSE_JOIN_CLASS + userId.toString()).getValue();
        model.addAttribute("classesUrl",classesUrl);
        loggerGenService.genGoodsPVUVLog(courseId, ShopType.ORDER_SHOP_COURSE);
        model.addAttribute("classes", classesService.getCourseRelevanceClasses(courseId));
        return resultPage("/course/cou/course-info");
    }

    /**
     * 获取课程目录
     * @param courseId   课程ID
     * @param courseType 课程类型
     * @return 目录页面
     */
    @RequestMapping("/findCourseCatalog")
    public String findCourseCatalog(HttpServletRequest request,
                                    Model model,
                                    @RequestParam("courseId") BigDecimal courseId,
                                    @RequestParam("courseType") String courseType, @RequestParam(value = "buyCourse",required = false,defaultValue ="" ) Boolean buyCourse) {
        //用户ID
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        //如果不是套餐课程
        if (!courseType.equals(CourseType.COURSE_TYPE_PACKAGE.getKey())) {
            List<Map<String, Object>> courseCatalogList = courseCatalogService.findCourseCatalogLayeredByCourseId(courseId,userId,courseId, true, false, false, false,true);
            model.addAttribute("courseCatalogList", courseCatalogList);
        } else {//如果是套餐课程
            //获取套餐下的所有的课程数据
            Map<Integer, List<Map<String, Object>>> packageCourseMap = packageCourseService.findUserLayeredPackageCourseByPackageId(userId, courseId, true);
            model.addAttribute("packageCourseMap", packageCourseMap);
        }
        model.addAttribute("courseType", courseType);
        model.addAttribute("buyCourse", buyCourse);
        model.addAttribute("courseIdParent",courseId);

        return resultPage("/course/cou/ajax-course-info-catalog");
    }

    /**
     * 加载直播目录
     * @param courseId 直播课程ID
     * @return 页面
     */
    @RequestMapping("/loadLiveCatalog")
    public String loadLiveCatalog(HttpServletRequest request,
                                  Model model,
                                  @RequestParam("courseId") BigDecimal courseId){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        List<Map<String, Object>> courseCatalogList = courseCatalogService.findCourseCatalogLayeredByCourseId(courseId,userId,courseId, true, false, false, false,false);
        model.addAttribute("courseCatalogList", courseCatalogList);
        return resultPage("/course/live/ajax-live-info-catalog");
    }

    /**
     * 通过讲师ID，获取讲师数据
     * @param teacherId 课程ID
     * @return Map<String,Object>
     */
    @RequestMapping("/findQaTeacherById")
    @ResponseBody
    public Map<String,Object> findQaTeacherById(@RequestParam("teacherId") BigDecimal teacherId){
        Map<String,Object> teacher = sysTeacherService.findQaTeacherById(teacherId);
        return ResultUtil.SUCCESS("查询成功",teacher);
    }

    /**
     * 检查是否购买课程/套餐
     *
     * @param courseId 课程id
     */
    @RequestMapping("/checkUserBuyCourse")
    @ResponseBody
    public Map<String, Object> checkUserBuyCourse(HttpServletRequest request,
                                                  @RequestParam("courseId") BigDecimal courseId) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> record = courseBuyRecordService.checkUserBuyCourse(userId, courseId);
        if (Objects.nonNull(record)) {
            if (CourseType.COURSE_TYPE_PACKAGE.getKey().equals(record.get("courseTypeKey"))) {
                if (!record.get("status").equals(1)) {
                    return ResultUtil.ERROR("套餐激活后才能评价与反馈");
                }
            }
        } else {
            return ResultUtil.ERROR("啊呀，提问功能是向学员开放的哦~~");
        }
        return ResultUtil.SUCCESS();
    }

    /**
     * 获取最新更新的目录数据
     * @param courseIds
     * @return Map<String,Object>
     */
    @RequestMapping("/getNewCatalog")
    @ResponseBody
    public Map<String,Object> getNewCatalog(@RequestParam("courseIds") String courseIds){
        Map<String,Object> catalog = courseCatalogService.getNewCourseCatalog(courseIds);
        return ResultUtil.SUCCESS(catalog);
    }


    /**
     * 下载课程章节资料
     * @param catalogId 课程id
     */
    @RequestMapping("/downloadDatum")
    public ResponseEntity<byte[]> downloadDatum(@RequestParam("catalogId") BigDecimal catalogId ) throws Exception {
        return courseCatalogService.downloadDatum(catalogId);

    }

    /**
     * 获取购买课程的用户数据列表
     * @param courseId 课程ID
     * @param currentPage 页码
     * @return Map<String,Object>
     */
    @RequestMapping("/findCourseBuyUserList")
    @ResponseBody
    public Map<String,Object> findCourseBuyUserList(@RequestParam("courseId") BigDecimal courseId,
                                                    @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage){
        Map<String,Object> orderDetailsList = courseService.findCourseBuyUserList(courseId,currentPage,12);
        return ResultUtil.SUCCESS(orderDetailsList);
    }


    /**
     * 用于引导用户去购买课程
     * @param request HttpServletRequest
     * @param courseId 课程ID
     * @return 详情页面
     */
    @RequestMapping("/guideBuyCourse")
    @ResponseBody
    public Map<String,Object> guideBuyCourse(HttpServletRequest request,
                             @RequestParam("courseId") BigDecimal courseId) {
        //用户ID
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);

        return   courseService.guideBuyCourse(courseId, userId,true, true, false, false, false, false,false);
    }

    /**
     * 获取课程可以领取的优惠券数据列表
     * @param courseId 课程ID
     * @return Map<String,Object>
     */
    @RequestMapping("/getCourseCouponList")
    @ResponseBody
    public Map<String,Object> getCourseCouponList(HttpServletRequest request,
                                                  @RequestParam("courseId") BigDecimal courseId){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        List<OpCoupon> couponList = opCouponService.getCourseCouponList(courseId,userId);
        return ResultUtil.SUCCESS(couponList);
    }

    /************************小班课*************************/
    /**
     * 小班课（列表）
     * @return
     */
    @RequestMapping("/smallClassIndex")
    public String smallClassIndex(){
        return resultPage("/course/smallClass/small-class");
    }



    /**
     * 加载课程数据
     * @param model Model
     * @param params 查询条件
     * @param currentPage 页码
     * @return String
     */
    @RequestMapping("/ajaxSmallClassIndex")
    public String ajaxSmallClassIndex(Model model,
                               @RequestBody Map<String, Object> params,
                               @RequestParam("currentPage") int currentPage) {
        params.put("status", 1);
        params.put("type", 4);
        params.put("courseTypeKey", CourseType.COURSE_TYPE_SMALL.getKey());
        Map<String, Object> dataMap = courseService.findWebCoursePage(params, currentPage, 6, true, false, false, true,true);
        model.addAttribute("dataMap", dataMap);
        return resultPage("/course/smallClass/ajax-small-class-index");
    }


    /**
     * 小班课（详情）
     * @return
     */
    @RequestMapping("/smallClassInfo")
    public String smallClassInfo(HttpServletRequest request, Model model, @RequestParam("courseId") BigDecimal courseId){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> course = courseService.findToBuyCourseById(courseId, userId,true, true, true, false, false, true,true);
        pageViewCountService.addPageCount(PageKeyUtils.COURSE_INFO, PageFrom.PAGE_FROM_PC);
        request.setAttribute("mobilePathShare", "/mobile/course/smallClassInfo?courseId="+courseId);
        model.addAttribute("course",course);
        course.put("courseService",CourseContentUtil.setCourseService(Integer.valueOf(course.get("service").toString()),sysConfigService," . "));
        loggerGenService.genGoodsPVUVLog(courseId, ShopType.ORDER_SHOP_COURSE);
        model.addAttribute("classes", classesService.getCourseRelevanceClasses(courseId));
        return resultPage("/course/smallClass/small-class-info");
    }

}
